//
//  CXRecommendViewController.m
//  Delicious
//
//  Created by dllo on 15/11/24.
//  Copyright © 2015年 doll. All rights reserved.
//

#import "CXRecommendViewController.h"
#import "CXBigCollectionViewCell.h"
#import "CXSmallCollectionViewCell.h"
#import "CXNetHandle.h"
#import "CXRecommendCollectionModel.h"
#import "MBProgressHUD.h"
#import "CXRecommendTableViewCell.h"
#import "CXRecommendModel.h"
#import "CXAdvertisementTableViewCell.h"
#import "CXRecommendHotModel.h"
#import "CXRecommendHotTableViewCell.h"
#import "CXImagesDetailViewController.h"
#import "Masonry.h"

@interface CXRecommendViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate>

//tableheadView
@property (nonatomic, retain) UIView *view_collection;
@property (nonatomic, retain) UITableView *tableView;
//大图
@property (nonatomic, retain) UICollectionView *collection_big;
//小图
@property (nonatomic, retain) UICollectionView *collection_small;
//轮播图
@property (nonatomic, retain) NSArray *arr_images;

//今日推荐
@property (nonatomic, retain) NSArray *arr_today;

//节日广告
@property (nonatomic, retain) NSDictionary *dic_advertisement;

//热门推荐
//@property (nonatomic, retain) UICollectionView *collection_hot;
@property (nonatomic, retain) NSArray *arr_hot;


@property (nonatomic, retain) MBProgressHUD *activity;


@end

@implementation CXRecommendViewController

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.translucent = NO;
    //self.automaticallyAdjustsScrollViewInsets = NO;
    
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"推荐";
    
    [self prepareData];
    [self createTableView];
    [self createCollectionImages];
    NSLog(@"%f", SCALE);
}

- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH , HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //注册tableView的cell
    [self.tableView registerClass:[CXRecommendTableViewCell class] forCellReuseIdentifier:@"recommendCell"];
    [self.tableView registerClass:[CXAdvertisementTableViewCell class] forCellReuseIdentifier:@"advertisementCell"];
    [self.tableView registerClass:[CXRecommendHotTableViewCell class] forCellReuseIdentifier:@"hotCell"];
    
}

#pragma mark - 准备数据
- (void)prepareData
{
    NSString *str_url = @"http://api.meishi.cc/v5/index2.php?format=json";
    NSString *str_body = @"body:lat=38.88270485803923&lon=121.5392473871113&source=iphone&format=json&page=1";
    [CXNetHandle postUrl:str_url parame:str_body cookie:nil result:^(id result) {
        //NSLog(@"%@", result);
        [self.activity removeFromSuperview];
        NSArray *arr_images_tmp = result[@"obj"][@"san_can"];
        self.arr_images = [CXRecommendCollectionModel transformWithArray:arr_images_tmp];
        NSArray *arr_top2_tmp = result[@"obj"][@"top2"];
        self.arr_today = [CXRecommendModel transformWithArray:arr_top2_tmp];
        self.dic_advertisement = result[@"obj"][@"top4"];
        
        //轮播图 (所有图片变亮变暗 isClear控制)
        for (CXRecommendCollectionModel *m in self.arr_images) {
            m.isClear = NO;
        }
        if (self.arr_images.count != 0)
        {
            // YES是暗  NO是亮的 第3张图变亮
            [self.arr_images[2] setIsClear:YES];
            // 初始偏移到第3个
            [self.collection_big setContentOffset:CGPointMake(WIDTH * 2, 0) animated:NO];
        }
        [self.collection_big reloadData];
        [self.collection_small reloadData];
        [self.tableView reloadData];
    }];
    
    
    NSString *str_url_hot = @"http://api.haodou.com/index.php?appid=4&appkey=573bbd2fbd1a6bac082ff4727d952ba3&appsign=def4efc026b6bcb0f90dde65187f5fc9&channel=appstore&deviceid=0f607264fc6318a92b9e13c65db7cd3c%7CA39FCC22-568D-4F9A-9E34-8103062B4879%7C9ED2A60C-F812-4F12-8B30-E11DA21CF5C3&format=json&loguid=8787440&method=Recipe.getAlbumList&nonce=1445391871&sessionid=1445391860&signmethod=md5&timestamp=1445391871&uuid=734104aa2129793874658cf97feb7dd4&v=2&vc=42&vn=v5.3.0";
    NSString *str_body_hot = @"limit=10&offset=0&sign=01411c539a3785b880b4bd4ee0c9340a&tagid=0&type=3&uid=8787440&uuid=734104aa2129793874658cf97feb7dd4";
    [CXNetHandle postUrl:str_url_hot parame:str_body_hot cookie:nil result:^(id result) {
        //NSLog(@"%@", result);
        self.arr_hot = result[@"result"][@"list"];
        [self.tableView reloadData];
    }];
    
}

#pragma mark - 创建轮播图
- (void)createCollectionImages
{
    self.view_collection = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, (264 + 84) * SCALE)];
    self.tableView.tableHeaderView = self.view_collection;
    NSLog(@"1111111%f", self.view_collection.frame.size.height);
    
    //创建大的collectioView
    UICollectionViewFlowLayout *layout_big = [[UICollectionViewFlowLayout alloc] init];
    //设置cell大小
    layout_big.itemSize = CGSizeMake(WIDTH, 264 * SCALE);
    //滚动方向(横向)
    layout_big.scrollDirection= UICollectionViewScrollDirectionHorizontal;
    //行间距
    layout_big.minimumLineSpacing = 0;
    
    self.collection_big = [[UICollectionView alloc ]initWithFrame:CGRectMake(0, 0, WIDTH, 264 * SCALE) collectionViewLayout:layout_big];
    self.collection_big.backgroundColor = [UIColor whiteColor];
    self.collection_big.dataSource = self;
    self.collection_big.delegate = self;
    self.collection_big.pagingEnabled = YES;
    self.collection_big.bounces = NO;
    [self.view_collection addSubview:self.collection_big];
    [self.collection_big registerClass:[CXBigCollectionViewCell class] forCellWithReuseIdentifier:@"bigCollectionViewItem"];
    NSLog(@"22222222%f", self.collection_big.frame.size.height);

    //创建小的CollectionView
    UICollectionViewFlowLayout *layout_small = [[UICollectionViewFlowLayout alloc] init];
    layout_small.itemSize = CGSizeMake(84 * SCALE, 84 * SCALE);
    layout_small.sectionInset = UIEdgeInsetsMake(10, 5, 10, 5);
    layout_small.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout_small.minimumLineSpacing = 5;
    
    self.collection_small = [[UICollectionView alloc] initWithFrame:CGRectMake(0, self.collection_big.frame.size.height , WIDTH, 84 * SCALE) collectionViewLayout:layout_small];
    self.collection_small.collectionViewLayout = layout_small;
    self.collection_small.contentSize = CGSizeMake(84 * SCALE * 15, 84 * SCALE);
    self.collection_small.backgroundColor = [UIColor whiteColor];
    self.collection_small.dataSource = self;
    self.collection_small.delegate = self;
    self.collection_small.bounces = NO;
    self.collection_small.pagingEnabled = NO;
    [self.view_collection addSubview:self.collection_small];
    [self.collection_small registerClass:[CXSmallCollectionViewCell class] forCellWithReuseIdentifier:@"smallCollectionCell"];
    NSLog(@"3333333%f", self.collection_small.frame.size.height);
    
//    [self.collection_big mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.right.mas_equalTo(self.view_collection);
//        //make.bottom.mas_equalTo(self.collection_small.mas_top);
//        make.height.mas_equalTo(@(280 * SCALE));
//    }];
//    [self.collection_small mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.mas_equalTo(self.collection_big.mas_bottom);
//        make.left.right.mas_equalTo(self.view_collection);
//        make.bottom.mas_equalTo(self.view_collection);
//    }];
    
    self.activity = [[MBProgressHUD alloc] initWithView:self.view];
    //self.activityView.backgroundColor = [UIColor grayColor];
    //self.activityView.dimBackground = YES;
    self.activity.labelText = @"正在加载";
    self.activity.labelFont = [UIFont systemFontOfSize:20];
    self.activity.labelColor = [UIColor whiteColor];
    [self.view addSubview:self.activity];
    [self.activity show:YES];
}

#pragma mark - 分区个数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 3;
}

#pragma mark - tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return 1;
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return @"今日推荐";
    }else if(section == 1){
        return nil;
    }else{
        return @"热门推荐";
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 230 * SCALE;
    }else if(indexPath.section == 1){
        return 100;
    }else if(indexPath.section == 2){
        return 340;
    }else{
        return 100;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        CXRecommendTableViewCell *recommendTodayCell = [tableView dequeueReusableCellWithIdentifier:@"recommendCell"];
        recommendTodayCell.model_today = self.arr_today[indexPath.row];
        return recommendTodayCell;
    }else if(indexPath.section == 1){
        CXAdvertisementTableViewCell *recommendAdvertisementCell = [tableView dequeueReusableCellWithIdentifier:@"advertisementCell"];
        recommendAdvertisementCell.dic_advertisement = self.dic_advertisement;
        return recommendAdvertisementCell;
    }else{
        CXRecommendHotTableViewCell *recommendHotCell = [tableView dequeueReusableCellWithIdentifier:@"hotCell"];
        recommendHotCell.arr_hot = self.arr_hot;
        return recommendHotCell;
    }
}

#pragma mark - collectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr_images.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collection_big) {
        CXBigCollectionViewCell *item_big = [collectionView dequeueReusableCellWithReuseIdentifier:@"bigCollectionViewItem" forIndexPath:indexPath];
        item_big.model_recommend = self.arr_images[indexPath.row];
        return item_big;
    }else{
        CXSmallCollectionViewCell *item_small = [collectionView dequeueReusableCellWithReuseIdentifier:@"smallCollectionCell" forIndexPath:indexPath];
        item_small.model_recommend = self.arr_images[indexPath.row];
        return item_small;
    }
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    if (collectionView == self.collection_big) {
        CXImagesDetailViewController *imagesVC = [[CXImagesDetailViewController alloc] init];
        imagesVC.model_inages = self.arr_images[indexPath.row];
        [self.navigationController pushViewController:imagesVC animated:YES];
    }else if (collectionView == self.collection_small){
        [self.collection_big scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.item inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        [self.collection_small scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:indexPath.item inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        
        for (CXRecommendCollectionModel *model in self.arr_images)
        {
            model.isClear = NO;
            
        }
        [self.arr_images[indexPath.row] setIsClear:YES];
        [collectionView reloadData];
        
        
    }else{
        
    }
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if (self.first == 1) {
//        
//    }else{
//        //判断滑动的是不是大的collectionView
//        if (scrollView == self.collection_big)
//        {
//            NSInteger currentItem = (scrollView.contentOffset.x) / WIDTH;
//            //NSIndexPath *indexPath = [NSIndexPath indexPathForItem:currentItem inSection:0];
//            
//            //        CXSmallCollectionViewCell *cell = [self.collection_small dequeueReusableCellWithReuseIdentifier:@"smallCollectionCell" forIndexPath:indexPath];
//            //        //cell.blackView.alpha = 0.0;
//            
//            //小的collectionView 也对应的滑到大的collectionView的item
//            [self.collection_small scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:currentItem inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
//            
//            for (CXRecommendCollectionModel *model in self.arr_images)
//            {
//                model.isClear = NO;
//            }
//            [self.arr_images[currentItem] setIsClear:YES];
//            [self.collection_small reloadData];
//        }
//        
//    }
//    
//}

#pragma mark - scrollViewDelegate(scrollView 即将结束)
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //判断滑动的是不是大的collectionView
    if (scrollView == self.collection_big)
    {
        NSInteger currentItem = (scrollView.contentOffset.x) / WIDTH;
        //NSIndexPath *indexPath = [NSIndexPath indexPathForItem:currentItem inSection:0];
        
        //        CXSmallCollectionViewCell *cell = [self.collection_small dequeueReusableCellWithReuseIdentifier:@"smallCollectionCell" forIndexPath:indexPath];
        //        //cell.blackView.alpha = 0.0;
        
        //小的collectionView 也对应的滑到大的collectionView的item
        [self.collection_small scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:currentItem inSection:0] atScrollPosition:UICollectionViewScrollPositionCenteredHorizontally animated:YES];
        
        for (CXRecommendCollectionModel *model in self.arr_images)
        {
            model.isClear = NO;
        }
        [self.arr_images[currentItem] setIsClear:YES];
        [self.collection_small reloadData];
        
        
    }
    
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
